#include <bits/stdc++.h>
using namespace std;
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
using ll = long long;
#define int long long
void solve()
{
    ll n, k;
    cin >> n >> k;
    ll ans = 0;
    ll sum = 0;
    vector<int> num(21, 0);
    for (ll bit = 20; bit >= 0; bit--)
    {
        int p = pow(3, bit);
        if (n >= p)
        {
            int cnt = n / p;
            num[bit] += cnt;
            sum += cnt;
            n -= p * cnt;
        }
    }
    if (sum > k)
    {
        cout << -1 << endl;
    }
    else
    {
        for (ll bit = 20; bit >=1; bit--)
        {
            int now = (k - sum) / 2;
            if (!now)
                break;
            if (now >= num[bit])
            {
                num[bit - 1] += num[bit] * 3;
                sum += num[bit] * 2;
                num[bit] = 0;
            }
            else
            {
                num[bit - 1] += now * 3;
                num[bit] -= now;
                sum += now * 2;
            }
        }
        auto pir = [&](int x) -> int
        {
            if (x == 0)
                return 3;
            return pow(3, x + 1) + x * pow(3, x - 1);
        };
        ans = 0;
        for (int bit = 20; bit >= 0; bit--)
        {
            ans += pir(bit) * num[bit];
        }
        cout << ans << endl;
    }
}
signed main()
{
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}
